package com.gcosc.hly.codejava.Utils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.util.List;


public class ExcelUtils {

    public static Workbook export(Workbook workbook, String sheetName, List list) {

        //创建表
        Sheet sheet = workbook.createSheet(sheetName);

        sheet.setDefaultColumnWidth(1000);
        sheet.setDefaultRowHeight((short) 200);

        try {

            //写入数据
            for (int rowNumber = 0; rowNumber < list.size() + 1; rowNumber++) {//行

                Row row = sheet.createRow(rowNumber);//行

                Object data = list.get(rowNumber - 1 == 0 ? rowNumber - 1 : 0);

                Class<?> dataClass = data.getClass();

                Field[] fields = dataClass.getDeclaredFields();

                for (int cellNumber = 0; cellNumber < fields.length; cellNumber++) {//列

                    Field field = fields[cellNumber];

                    field.setAccessible(true);

                    Cell cell = row.createCell(cellNumber);

                    if (rowNumber == 0){
                        cell.setCellValue(field.getName());
                        continue;
                    }

                    Object o = field.get(data);

                    cell.setCellValue(o == null ? "" : o.toString());

                }

            }
            //
            //FileOutputStream fileOutputStream = new FileOutputStream("用户信息表-XLSX.xlsx");
            //workbook.write(fileOutputStream);
            //fileOutputStream.close();

        }catch (Exception e){
            e.printStackTrace();
        }

        return workbook;
    }


    public static Workbook export(String sheetName, List list) {
        return export(new XSSFWorkbook(), sheetName, list);
    }

    public static void export(String sheetName, List list, HttpServletResponse response) {
        try {
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;fileName=" + sheetName + ".xlsx");
            export(new XSSFWorkbook(), sheetName, list).write(response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
